class Car {
    constructor() {
        // 触发购物车列表
        this.getCarList();
        // 全选按钮的事件
        this.$('.selectAndImage input').addEventListener('click', this.allCheckFn);
        //  购物的按钮,采用事件委托,触发点击分割函数
        this.$('.cartProductTable tbody').addEventListener('click', this.clickEvery)
    }
    /* ***获取购物车列表*** */
    async getCarList() {
        // 获取locastorage中的id和token
        let id = localStorage.getItem('id');
        const AUTH_TOKEN = localStorage.getItem('token');
        axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
        // console.log(id);
        //发送请求购物车列表
        let res = await axios.get('http://localhost:8888/cart/list?id=' + id);
        // console.log(res);
        if (res.data.code == 0 && res.status == 200) {
            location.assign('login.html?comeFrom=car.html')
        }
        if (res.data.code == 401 && res.status == 200) {
            location.assign('login.html?comeFrom=car.html')
        }
        let str = '';
        let ele = res.data.cart;
        console.log(ele);
        ele.forEach(element => {
            str += `<tr class="cartProductItemTR" oiid="936" style="background-color: rgb(255, 255, 255);" data-id=${element.goods_id}>
            <td>
                <span><input type="checkbox" class='goodsInput'></span>
                <img class="cartProductImg" src="${element.img_small_logo}">
            </td>
            <td>
                <div class="cartProductLinkOutDiv">
                    <a class="cartProductLink" href="#nowhere">${element.title}</a>
                    
                </div>
            </td>
            <td>
                <span class="cartProductItemOringalPrice">￥${element.price}</span>
                <span class="cartProductItemPromotionPrice">￥${element.current_price}</span>
            </td>
            <td>
                <div class="cartProductChangeNumberDiv">
                    <a class="numberMinus" href="#nowhere" pid="365">-</a>
                    <input autocomplete="off" class="orderItemNumberSetting" oiid="936" pid="365" value="${element.cart_number}">
                    <a class="numberPlus" href="#nowhere" pid="365" stock="75">+</a>
                </div>
            </td>
            <td>
                <span class="cartProductItemSmallSumPrice" oiid="936" pid="365">
                    ￥${(element.current_price * element.cart_number).toFixed(2)}
                </span>
            </td>
            <td>
                <a class="deleteOrderItem" href="#nowhere" oiid="936">删除</a>
            </td>
        </tr>`
        });
        //获取页面中的节点
        this.$('.cartProductTable tbody').innerHTML = str;
        // console.log(this.$('.cartProductTable tbody'));
    }
    /* *****点击全选按钮触发的事件***** */
    allCheckFn = () => {
        // console.log(1111);
        //获取input
        let allCheckObj = window.event.target;
        // console.log(allCheckObj);
        //触发遍历所有商品input的方法
        this.eachInput(allCheckObj.checked);
    }
    /* *****遍历所有商品input的方法***** */
    eachInput(att) {
        // console.log(att);
        //获取所有的商品的input
        let inputEle = this.$('.cartProductTable tbody span input');
        // console.log(inputEle);
        //转化为数组
        let inputArray = [...inputEle];
        // console.log(inputArray);
        inputArray.forEach(ele => {
            ele.checked = att;
        })
        this.sum();
    }
    /* *****购物车的点击分解函数***** */
    clickEvery = () => {
        let targetObj = window.event.target;
        // console.log(targetObj);
        //判断如果为input则触发inputClick事件
        if (targetObj.classList.contains('goodsInput')) {
            // console.log(1111);
            this.inputClick(targetObj);
        }
        //如果判断为删除二字则触发deleteClick事件
        if (targetObj.classList.contains('deleteOrderItem')) {
            // console.log(1111);
            this.deleteClick(targetObj);
        }
        //判断如果为加号则触发upNumClick事件
        if (targetObj.classList.contains('numberPlus')) {
            // console.log(1111);
            this.upNumClick(targetObj);
        }
        //判断如果为减号则触发upNumClick事件
        if (targetObj.classList.contains('numberMinus')) {
            // console.log(1111);
            this.downNumClick(targetObj);
        }
    }
    /* ***点击购物车的input触发的inputClick事件 */
    inputClick() {
        //获取所有的商品的input
        let inputEle = this.$('.cartProductTable tbody span input');
        // 获取购物车的input
        let allCheckEle = this.$('.selectAndImage input');
        // console.log(inputEle);
        //转化为数组
        let inputArray = [...inputEle];
        //every遍历所有的选择状态,都为true,则全选也为true
        let result = inputArray.every(ele => ele.checked);
        // console.log(result);
        allCheckEle.checked = result;
        this.sum();
    }
    /* ***点击删除触发的deleteClick事件 */
    async deleteClick(targetObj) {
        // console.log(1111);
        // 触发获取tr节点的方法
        let trObj = this.select(targetObj);
        // console.log(trObj);
        //获取要删除的商品id
        let goodsId = trObj.dataset.id;
        // console.log(goodsId);
        //获取用户id
        let id = localStorage.getItem('id')
        let str = `goodsId=${goodsId}&id=${id}`
        // console.log(goodsId,id);
        let res = await axios.get('http://localhost:8888/cart/remove?' + str);
        // console.log(res);
        if (res.data.code == 1 && res.status == 200) {
            trObj.remove();
        }
        this.sum();
    }
    /* ***点击加号则触发的upNumClick事件 */
    upNumClick(targetObj) {
        // console.log(1111);
        // 获取商品数量的input框
        let Obj = this.select(targetObj);
        let goodsNum = Obj.querySelector('.orderItemNumberSetting');
        // console.log(goodsNum);
        //获取商品id
        let goodsId = this.select(targetObj).dataset.id;
        // console.log(goodsId);
        //现有页面上的商品数量修改
        let num = goodsNum.value - 0;
        num++;
        goodsNum.value = num;
        //进行页面中单件商品总金额的改变
        this.sumMoney(goodsId,targetObj);
        //设置防抖
        clearTimeout(this.clickQuickly1);
        this.clickQuickly1 = setTimeout(() => {
            //触发提交数据的方法,和减号公用
            this.goodsNumFn(num, goodsId);
            // console.log(num);
        }, 500)
        this.sum();
    }
    /* ***点击减号则触发的downNumClick事件 */
    downNumClick(targetObj) {
        // console.log(1111);
        // 获取商品数量的input框
        let Obj = this.select(targetObj);
        let goodsNum = Obj.querySelector('.orderItemNumberSetting');
        // console.log(goodsNum);
        //获取商品id
        let goodsId = this.select(targetObj).dataset.id;
        // console.log(goodsId);
        //现有页面上的商品数量修改
        let num = goodsNum.value - 0;
        if (num > 1) { num-- }
        goodsNum.value = num;
        //进行页面中单件商品总金额的改变
        this.sumMoney(goodsId,targetObj);
        //设置防抖
        clearTimeout(this.clickQuickly2);
        this.clickQuickly2 = setTimeout(() => {
            //触发提交数据的方法,和加号公用
            this.goodsNumFn(num, goodsId);
            // console.log(num);
        }, 500)
        this.sum();
    }
    //被加减号触发的goodsNumFn事件
    async goodsNumFn(num, goodsId) {
        // console.log(num , goodsId);
        // 获取参数名称并进行组合
        //获取id
        let id = localStorage.getItem('id');
        let str = `id=${id}&goodsId=${goodsId}&number=${num}`

        let res = await axios.post('http://localhost:8888/cart/number', str)
        // console.log(res);
    }
    /* *****获取小计金额*** */
    sumMoney(goodsId,targetObj) {
        //获取单件金额
        let Obj = this.select(targetObj);
        // 获取商品数量的input框
        let goodsNum = Obj.querySelector('.orderItemNumberSetting');
        // console.log(goodsNum);5
        let number = goodsNum.value - 0;
        let Price = Obj.querySelector('.cartProductItemPromotionPrice').innerHTML.split('￥').pop()-0;
        // console.log(Price);
        //获取总金额
        let sumPrice = Obj.querySelector('.cartProductItemSmallSumPrice');
        // console.log(sumPrice);
        // console.log(Price,number);
        sumPrice.innerHTML ='￥'+ (Price * number).toFixed(2);
    }
    /* ***获取合计金额*** */
    sum(){
        //获取所以的input的选择情况
         // console.log(att);
        //获取所有的商品的input
        let inputEle = this.$('.cartProductTable tbody span input');
        // console.log(inputEle);
        //循环判断其checked状态
        let sum=0;
        let num=0;
        // 准备往结算页传递的数据,及商品id
        let str='';
        inputEle.forEach(ele =>{
            if(ele.checked){
                let sumObj=this.select(ele).querySelector('.cartProductItemSmallSumPrice');
                // console.log(xjObj);
                sum+=sumObj.innerHTML.split('￥').pop()-0;
                let numObj=this.select(ele).querySelector('.orderItemNumberSetting');
                // console.log(numObj);
                num+=numObj.value-0;
                let goodsId = this.select(ele).dataset.id;
                str+=`${goodsId}&`
            }
        })
        // console.log(sum,num,str);
        // 获取页面中需要设置总价和总量的节点
        this.$('.cartSumNumber').innerHTML=num;
        this.$('.cartSumPrice').innerHTML='￥'+(sum).toFixed(2);
        this.$('.cartTitlePrice').innerHTML='￥'+(sum).toFixed(2);
        //在此处使结算按钮变为红色,并赋予事件
        // console.log(this.$('.createOrderButton'));
        this.$('.createOrderButton').forEach(ele=>{
            ele.style.backgroundColor='red';
            ele.addEventListener('click',()=>{
                location.assign('settlement.html?'+str)
            })
        })
    }
    /* *****自动向上寻找父节点的回调函数方法***** */
    select(ele) {
        if (ele.classList.contains('cartProductItemTR')) {
            return ele;
        }
        return this.select(ele.parentNode);
    }
    /* *****获取节点的方法****** */
    $(ele) {
        let node = document.querySelectorAll(ele)
        return node.length == 1 ? node[0] : node;
    }
}
new Car;